import axios from "axios";
axios.create({
  timeout: 10 * 1000,
});
axios.defaults.baseURL = "/myapi";
export const getAuthorization = () => localStorage.getItem("USER_DATA");
export const getAuthorizationToken = () => localStorage.getItem("USER_TOKEN");

//添加请求拦截器
axios.interceptors.request.use(
  async (config) => {
    config.headers.Authorization = getAuthorizationToken();
    return config;
  },
  (error) => {
    //请求错误时做些事
    return Promise.reject(error);
  }
);

//添加响应拦截器
axios.interceptors.response.use(
  async (response) => {
    if(response.headers.authorization){
      localStorage.clear();
      localStorage.setItem("USER_TOKEN", response.headers.authorization);
    }
    if (response?.data?.code == 401) {
      if (location?.hash !== "#/login") {
        location.hash = "/login";
      }
      localStorage.clear();
      return;
    }
    return response;
  },
  (error) => {
    //请求错误时做些事
    if (error?.response?.status == 401) {
      if (location?.hash !== "#/login") {
        location.hash = "/login";
      }
      localStorage.clear();
      
      return Promise.reject(error?.response);
    }
    return Promise.reject(error);
  }
);

//统一接口处理，返回数据
const request = (fecth, url, param, data, header) => {
  return new Promise((resolve, reject) => {
    switch (fecth) {
      case "get":
        axios
          .get(url, {
            params: param,
          })
          .then((response) => {
            resolve(response.data);
          })
          .catch((error) => {
            reject(error);
          });
        break;
      case "post":
        axios({
          method: "post", //请求方式，默认是get请求
          url,
          params: param,
          data,
          header,
        })
          .then((response) => {
            resolve(response.data);
          })
          .catch((error) => {
            reject(error);
          });
        break;
      case "delete":
        axios.delete(url, param, header).then(
          (response) => {
            resolve(response.data);
          },
          (err) => {
            reject(err);
          }
        );
        break;
      default:
        break;
    }
  });
};

export default request;
